﻿/**
 * @class tuan.controllerLoginController
 * @extends extendsClass
 * Description
 */
 Ext.define('tuan.controller.LoginController', {
    extend: 'Ext.app.Controller',
    refs: [
    { ref: "userName", selector: "login textfield[id=usernametext]" },
    { ref: "password", selector: "login #passwordtext" }
    ],
    views : ["LoginScreen"],
    init : function(){
        this.control({
            "#loginbutton" : {
                click : this.authenticate
            }
        })
    },
    authenticate : function(){
        username = this.getUserName().getValue();
        password = this.getPassword().getValue();

        var viewPortApp = this.application.viewport;
        Ext.Ajax.on("beforerequest", function(){
            Ext.getBody().mask("Loading...", 'loading');
        });
        Ext.Ajax.on("requestcomplete", function(){
            window.parent.Ext.getBody().unmask();
        });
        Ext.Ajax.on("requestexception", function(){
            Ext.Msg.alert('Error','Sorry something wrong!');
            window.parent.Ext.getBody().unmask();
        });
        Ext.Ajax.request({
            url : tuan.config.Runtime.linkUrl+"Login/login",
            params: {
                username : username,
                password : password,
                // action   : "check_login_action",
            },
            success: function(response){
                var re  = response.responseText;
                re = Ext.decode(re);
                var text = re.statusLogin;
                var level = re.level;
                if(text === "success"){
                    //Ext.Msg.alert('Success','Login Success');
                    sessionStorage.setItem('sessionUser', "yes");
                    sessionStorage.setItem('username', username);
                    sessionStorage.setItem('level', level);
                    viewPortApp.add({ xtype: "home", id: "homescreen"});
                    viewPortApp.getLayout().setActiveItem(1);//customer
                    Ext.getCmp("center_panel").getLayout().setActiveItem(3);

                }else if(text === "fail"){
                    Ext.Msg.alert('Fail','Login fail, check username, password');
                }else{
                    Ext.Msg.alert('Error','Login fail');
                }
            },
            failure: function () {
                Ext.Msg.alert('Error','Sorry something wrong!');
            }
        });
    }
});